<?php
/**
 * User: Kris
 * Date: 1/17/12
 */

require_once APPPATH . 'core/controller.php';

class PostController extends Controller
{

    public function __construct()
    {
        parent::__construct();

        $this->load->library('form_validation');
        $this->data['styles'][] = '/public/css/post.css';
    }

    public function create()
    {
        $query = $this->em->createQuery("SELECT c FROM Channel c JOIN c.owner u WHERE u.id = :userId");
        $query->setParameter('userId', $this->session->userdata('userId'));

        $channels = $query->getResult();
        $this->data['channels'] = $channels;

        //$this->em->getRepository('Channel')->findOneBy(array('name' => "test"));

        $this->parser->parse("post/create.tpl", $this->data);
    }

    public function insert()
    {
        $this->form_validation->set_rules('title', 'Titel', 'required');
        $this->form_validation->set_rules('content', 'Inhoud', 'required');
        $this->form_validation->set_rules('category', 'Category', 'callback_valid_category');
        $this->form_validation->set_error_delimiters('', '');

        $this->form_validation->set_message('required', "Het veld '%s' is vereist om een nieuwsbericht toe te voegen");


        if ($this->form_validation->run() == false) {
            $this->create();
        }
        else
        {
            $this->persistPost();
        }
    }

    public function valid_category($string)
    {
        return $this->em->find('Category', $string) != null;
    }

    private function persistPost()
    {
        $author = $this->em->find('User', $this->session->userdata('userId'));

        $title = $this->input->post('title', true);

        $content = new Post_Content();
        $content->setContent($this->input->post('content'));

        $category = $this->em->find('Category', $this->input->post('category'));

        $newPost = new Post();
        $newPost->setAuthor($author);
        $newPost->setTitle($title);
        $newPost->setContent($content);
        $newPost->setCategory($category);

        $channel = $this->em->find('Channel', $this->input->post('channel'));

        //$newPost->addChannel($channel);


        if ($this->input->post('tags')) {
            foreach ($this->input->post('tags') as $tagName)
            {
                $tag = $this->em->getRepository('Tag')->findOneBy(array('name' => $tagName));

                if ($tag == null) {
                    $tag = new Tag();
                    $tag->setName($tagName);
                }
                $newPost->addTag($tag);
            }
        }
        $this->em->persist($newPost);

        if($channel != null)
        {
            $channel->addPost($newPost);
        }

        foreach ($_FILES as $key => $value)
        {
            $media = $this->uploadFile($key);

            if ($media != null) {
                $media->setPost($newPost);
                $uploadNumber = end(explode('_', $key));
                $media->setDescription($this->input->post('description_uf_' . $uploadNumber));
                $this->em->persist($media);
            }
        }

        $this->em->flush();

        redirect("post/read/" . $newPost->getId(), "location");
    }

    /**
     * @param $id int
     */
    public function read($id)
    {
        $this->data['styles'][] = '/public/css/view.css';
        $this->data['styles'][] = '/public/css/comment-index.css';
        $post = $this->em->find('Post', $id);
        $this->data['postToView'] = $post;
        $post->addReadCount();

        $this->em->flush();

        $this->data['postHasTweets'] = false;
        foreach($post->getTags() as $tag)
        {
            if(substr($tag->getName(), 0, 1) == '#')
            {
                $this->data['postHasTweets'] = true;
                $this->loadTweets($tag->getName());
                break;
            }
        }

        $this->parser->parse("post/read.tpl", $this->data);
    }

    /**
     * @param $search string
     */
    private function loadTweets($search)
    {
        $data['tweets'] = array();
        $jsonContent = file_get_contents("http://search.twitter.com/search.json?q=" . urlencode($search) . "&lang=en&rpp=5");
        if ($jsonContent) {
            $tweets = json_decode($jsonContent);
            $this->data['tweets'] = $tweets->results;
        }
    }

    /**
     * @param $id int
     * @param $sure boolean
     */
    public function delete($id, $sure)
    {

    }

    /**
     * @var CI_UPLOAD
     */
    public $upload;

    /**
     * @param $key string
     * @return Media
     */
    public function uploadFile($key)
    {
        $this->load->library('upload');
        $this->upload->set_upload_path('./uploads/');


        if ($this->upload->validate_upload_path()) {
            $fileExtension = end(explode('.', $_FILES[$key]['name']));
            $fileName = sha1(microtime()) . '.' . $fileExtension;
            $config = array();
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png|jpeg';
            $config['file_name'] = $fileName;

            $this->upload->initialize($config);

            if (!$this->upload->do_upload($key)) {
                return null;
            }

            $media = new Media();
            $media->setLocation($fileName);
            $this->resizeImage($fileName);
            $this->createThumb($fileName);
            return $media;
        }
        return null;
    }

    /**
     * @var CI_Image_lib
     */
    public $image_lib;

    private function createThumb($fileName)
    {
        $this->load->library('image_lib');

        $config['image_library'] = 'gd2';
        $config['source_image'] = './uploads/' . $fileName;

        $config['maintain_ratio'] = FALSE;
        $config['width'] = 100;
        $config['height'] = 100;
        $config['new_image'] = './uploads/thumbs/thumb_' . $fileName;

        $this->image_lib = new CI_Image_lib($config);

        $this->image_lib->resize();
    }

    private function resizeImage($fileName)
    {
        $this->load->library('image_lib');

        $config['image_library'] = 'gd2';
        $config['source_image'] = './uploads/' . $fileName;

        $config['maintain_ratio'] = TRUE;
        $config['width'] = 480;
        $config['height'] = 360;

        $this->image_lib = new CI_Image_lib($config);

        $this->image_lib->resize();
    }

    public function printView($id)
    {
        $this->data['postToView'] = $this->em->find('Post', $id);
        $this->em->flush();
        $this->parser->parse("post/print_view.tpl", $this->data);
    }
}
